package com.jeeplus.modules.guide.service;

import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.Result;
import com.jeeplus.modules.guide.mapper.*;
import com.jeeplus.modules.guide.model.constant.GuideConstant;
import com.jeeplus.modules.guide.model.domain.*;
import com.jeeplus.modules.guide.model.enums.RecommendEnums;
import com.jeeplus.modules.guide.model.query.CancelAppointment;
import com.jeeplus.modules.guide.model.query.ModAppointment;
import com.jeeplus.modules.guide.model.query.ServiceOfficesQuery;
import com.jeeplus.modules.guide.model.vo.*;
import com.jeeplus.modules.guide.task.Send;
import com.jeeplus.modules.guide.utils.DistanceUtils;
import com.jeeplus.modules.guide.utils.RandomUtils;
import com.jeeplus.modules.guide.model.domain.WorkdayInfo;
import com.jeeplus.modules.sys.entity.MobileUserQR;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.sys.utils.UserUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * ClassName: AppointmentGuideService
 * Function:  预约指南
 * Date:      2021/6/3 14:21
 *
 * @author hanKongbin
 * version    V1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AppointmentService {


    private final HisQueueService hisQueueService;

    private final CurrentQueueService currentQueueService;

    private final WorkdayMapper workdayMapper;

    private final AppointmentQuotaMapper appointmentQuotaMapper;

    private final AppointmentRecordService appointmentRecordService;

    private final MobileMatterMapper mobileMatterMapper;

    private final MatterAreaMapper matterAreaMapper;

    private final UserService userService;

    private final MobileQueueService mobileQueueService;

    private final Send send;
    protected Logger logger = LoggerFactory.getLogger(AppointmentService.class);

    /**
     * 查询服务网点信息
     *
     * @param query
     * @return
     */
    public Result<ServiceOffices> findServeOffices(ServiceOfficesQuery query) {
        try {
            // 获取三方事项办理网点
            List<Offices> offices = getServeOffices(query.getMatterId());
            if (CollectionUtils.isEmpty(offices)) {
                log.error("事项未关联网点，事项id->{}", query.getMatterId());
                return Result.failed("没有可办理的网点！");
            }

            // 组装服务网点信息
            List<ServiceOffices.Detail> officesDetails = offices.stream().map(e ->
                    ServiceOffices.Detail.builder()
                            .id(e.getId())
                            .address(e.getAddress())
                            .position(new Double[]{e.getLongitude(), e.getLatitude()})
                            .type(e.getType())
                            .title(e.getTitle())
                            .tel(e.getTel())
                            .distance(Math.round(DistanceUtils.getDistance(query.getPosition(), new Double[]{e.getLongitude(), e.getLatitude()}) * 100.0D) / 100.0D)
                            .build()).collect(Collectors.toList());
            // 根据三方事项获取各个网点的预约业务
            Map<String, BusinessInfo> businessMap = queryAreaBusiness(query.getMatterId(), offices.stream().map(Offices::getId).collect(Collectors.toList()));
            List<String> businessIds = businessMap.values().stream().map(BusinessInfo::getTypeId).collect(Collectors.toList());
            // 根据业务id获取业务名称
            List<BusinessInfo> businessInfoDetails = appointmentRecordService.queryBusiness(businessIds);
            // key:业务id ; value:业务名称
            Map<String, String> bMap = businessInfoDetails.stream().collect(Collectors.toMap(BusinessInfo::getTypeId, BusinessInfo::getTypeName, (o1, o2) -> o1));
            for (ServiceOffices.Detail d : officesDetails) {
                BusinessInfo businessInfo = businessMap.get(d.getId());
                if (null == businessInfo) {
                    d.setTotalTime(GuideConstant.OFFICES_LIMIT_TIME);
                    log.error("事项未绑定业务，事项id->{}，区域id->{}", query.getMatterId(), d.getId());
                    continue;
                }
                // 根据业务查询 网点的 平均等待时间、平均办理时间
                HisQueue hisQueue = hisQueueService.getHistoryQueueTime(businessInfo.getTypeId(), d.getId());
                // 根据业务查询 等待人数
                QueueInfo queues = currentQueueService.getCurrentQueue(businessInfo.getTypeId(), d.getId());
                d.setBusinessId(businessInfo.getTypeId());
                d.setBusinessName(bMap.get(businessInfo.getTypeId()));
                if (null != hisQueue) {
                    d.setHandleTime(hisQueue.getDoTime() <= 0 ? 5:hisQueue.getDoTime());
                    d.setWaitTime(hisQueue.getWaitTime() <= 0 ? 5:hisQueue.getWaitTime());
                }
                if (null != queues) {
                    d.setWaitNum(queues.getWaitCount());
                }
            }
            // 过滤出未绑定业务的网点信息
            officesDetails = officesDetails.stream().filter(e -> StringUtils.isNotEmpty(e.getBusinessId())).collect(Collectors.toList());
            // 办理推荐
            setRecommend(officesDetails);
            List<String> list = matterAreaMapper.selectMapByMatterId(query.getMatterId());
            for(String str : list){
                for(ServiceOffices.Detail de : officesDetails){
                    if(str.equals(de.getBusinessId())){
                        de.setIsDoYY(false);
                    }
                }
            }
            return Result.succeed(ServiceOffices.builder()
                    .count(officesDetails.size())
                    .serviceOffices(officesDetails)
                    .build(), "");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return Result.failed("获取失败，请稍后再试！");
    }

    /**
     * 获取预约时间
     *
     * @param sysNo      网点编号
     * @param businessId 业务id
     * @return
     */
    public List<ServiceTime> getServiceTime(String sysNo, String businessId) {
        // 时段
        List<Integer> timePeriod = Arrays.asList(9, 10, 11, 12, 13, 14, 15, 16);
        // 工作日
        try {
            List<String> workdays = workdayMapper.queryWorkDay(10);
            GregorianCalendar calendar = new GregorianCalendar();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);

            if (CollectionUtils.isEmpty(workdays)) {
                return new ArrayList<>();
            }
            List<ServiceTime> data = workdays.stream().map(e ->
                    ServiceTime.builder()
                            .time(e)
                            .week(DateUtils.getWeek(DateUtils.parseDate(e)))
                            .details(timePeriod.stream().map(this::getTimeDetails).collect(Collectors.toList()))
                            .build()).collect(Collectors.toList());
            // 预约名额
            List<AppointmentQuota> maxQuotas = appointmentQuotaMapper.queryQuota(businessId, sysNo);
            Map<Integer, AppointmentQuota> maxQuotasMap = maxQuotas.stream().collect(Collectors.toMap(AppointmentQuota::getTimePeriod, Function.identity()));
            // 预约历史记录
            List<AppointmentRecord> records = appointmentRecordService.queryAppointmentRecords(sysNo, businessId, workdays, null);
            // 业务预约名额
            Map<String, List<AppointmentRecord>> recordsMap = records.stream().collect(Collectors.groupingBy(e -> DateUtils.formatDate(e.getApptDate(), DateUtils.PATTERN_YYYYMMDD)));
            Calendar ca = Calendar.getInstance() ;
            String time = ca.get(Calendar.AM_PM) == Calendar.AM?"上午":"下午";
            for (ServiceTime datum : data) {

                List<AppointmentRecord> timeRecord = recordsMap.get(datum.getTime());
                Map<Integer, AppointmentRecord> timeRecordMap = new HashMap<>();
                if (null != timeRecord) {
                    timeRecordMap = timeRecord.stream().collect(Collectors.toMap(AppointmentRecord::getTimePeriod, Function.identity()));

                }
                List<ServiceTime.Detail> d = datum.getDetails();
                for (ServiceTime.Detail detail : d) {
                    if(detail.getTimePeriod() < hour && datum.getTime().equals(DateUtils.getDate())){
                        detail.setQuota(0);
                        continue;
                    }else if(time.equals("上午") && detail.getTimePeriod() < 12 && datum.getTime().equals(DateUtils.getDate("yyyy-MM-dd"))){
                        detail.setQuota(0);
                        continue;
                    }
                    AppointmentRecord r = timeRecordMap.get(detail.getTimePeriod());
                    AppointmentQuota m = maxQuotasMap.get(detail.getTimePeriod());
                    int count = null != m ? m.getQuota() : 0;
                    if (null != r) {
                        if(count >= r.getCount())detail.setQuota(count - r.getCount());
                        else {
                            detail.setQuota(0);
                        }
                        continue;
                    }
                    detail.setQuota(count);
                }
                datum.setQuota(d.stream().mapToInt(ServiceTime.Detail::getQuota).sum());
            }

            if(time.equals("下午"))data.remove(0);
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取预约时间失败！");
        }
        return new ArrayList<>();
    }

    public BusinessAnalyze getBusinessAnalyze(String sysNo, String businessId) {
        BusinessAnalyze data = new BusinessAnalyze();
        try {
            data.setFirstWeek(getAnalyzeData(sysNo, businessId, getBeforeWeek(-1)));
            data.setSecondWeek(getAnalyzeData(sysNo, businessId, getBeforeWeek(-2)));
            data.setThirdWeek(getAnalyzeData(sysNo, businessId, getBeforeWeek(-3)));
            data.setFourthWeek(getAnalyzeData(sysNo, businessId, getBeforeWeek(-4)));
            data.setFutureWeek(getFutureData(data, getBeforeWeek(1)));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取失败！->{}", e.getMessage());
        }
        return data;
    }

    public BusinessAnalyze getBusinessAdmin() {
        BusinessAnalyze data = new BusinessAnalyze();
        try {
            data.setFirstWeek(getAnalyzeDataS("1",getBeforeWeek(0)));
            data.setSecondWeek(getAnalyzeDataS("2",getBeforeWeek(0)));
            data.setThirdWeek(getAnalyzeDataS("3",getBeforeWeek(0)));
            data.setFourthWeek(getAnalyzeDataS("4",getBeforeWeek(0)));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取失败！->{}", e.getMessage());
        }
        return data;
    }

    private List<BusinessAnalyze.Detail> getAnalyzeData(String sysNo, String businessId, List<WorkdayInfo> beforeWeek) {

        List<BusinessAnalyze.Detail> details = new ArrayList<>();

        if (CollectionUtils.isEmpty(beforeWeek)) {
            return details;
        }
        List<AvgPeople> avgPeople = hisQueueService.avgPeopleByBusinessId(businessId, sysNo, beforeWeek.get(0).getTime(), beforeWeek.get(beforeWeek.size() - 1).getTime());

        for (WorkdayInfo workday : beforeWeek) {
            BusinessAnalyze.Detail detail = new BusinessAnalyze.Detail();
            for (AvgPeople avgPerson : avgPeople) {
                if (Objects.equals(workday.getTime(), avgPerson.getTime())) {
                    detail.setCount(avgPerson.getCount());
                    break;
                }
            }
            detail.setWeek(workday.getWeekday());
            detail.setTime(workday.getTime());
            details.add(detail);
        }
        return details;
    }

    private List<BusinessAnalyze.Detail> getAnalyzeDataS(String type,List<WorkdayInfo> beforeWeek) {

        List<BusinessAnalyze.Detail> details = new ArrayList<>();

        if (CollectionUtils.isEmpty(beforeWeek)) {
            return details;
        }
        List<AvgPeople> avgPeople = hisQueueService.avgPeopleAll(type,beforeWeek.get(0).getTime(), beforeWeek.get(beforeWeek.size() - 1).getTime());

        for (WorkdayInfo workday : beforeWeek) {
            BusinessAnalyze.Detail detail = new BusinessAnalyze.Detail();
            for (AvgPeople avgPerson : avgPeople) {
                if (Objects.equals(workday.getTime(), avgPerson.getTime())) {
                    detail.setCount(avgPerson.getCount());
                    break;
                }
            }
            detail.setWeek(workday.getWeekday());
            detail.setTime(workday.getTime());
            details.add(detail);
        }
        return details;
    }

    private List<BusinessAnalyze.FutureDetail> getFutureData(BusinessAnalyze data, List<WorkdayInfo> afterWeek) {

        List<BusinessAnalyze.FutureDetail> details = new ArrayList<>();
        int count;
        for (int i = 0; i < afterWeek.size(); i++) {
            BusinessAnalyze.FutureDetail detail = new BusinessAnalyze.FutureDetail();
            count = data.getFirstWeek().get(i).getCount() + data.getSecondWeek().get(i).getCount() + data.getThirdWeek().get(i).getCount() + data.getFourthWeek().get(i).getCount();
            detail.setTime(afterWeek.get(i).getTime());
            detail.setWeek(afterWeek.get(i).getWeekday());
            detail.setCount(count / 4);
            detail.setTrendCount(detail.getCount() / 2);
            details.add(detail);
        }
        return details;
    }


    /**
     * 保存预约
     *
     * @param mod
     * @return
     */
    public synchronized Result<ModAppointmentOut> saveAppointment(ModAppointment mod,Boolean isOther,String idcard,String tell,String name) {
        LocalTime currentTime = LocalTime.now();
        int currentHour = currentTime.getHour();
        if(currentHour <= 7){
            return Result.failed("当前不可预约！");
        }
        if (null == mod || StringUtils.isEmpty(mod.getBusinessId()) || StringUtils.isEmpty(mod.getTime()) || StringUtils.isEmpty(mod.getSysNo()) || null == mod.getTimePeriod()) {
            return Result.failed("参数不合法！");
        }
        MobileUserQR qr = null;
        try {
            if (StringUtils.isEmpty(UserUtils.getUser().getLoginName()) && !isOther) {
                return Result.failed("用户未登录！");
            }
            if(!isOther){
                qr = userService.getUserIdcard(UserUtils.getUser().getLoginName());
                if (null == qr) {
                    return Result.failed("用户未绑定！");
                }
            }else{
                qr = new MobileUserQR();
                qr.setIdcard(idcard);
                qr.setTell(tell);
                qr.setName(name);
            }
            synchronized (this){
                // 取票预计时间
                if (DateUtils.isSameDay(DateUtils.parseDate(mod.getTime(), DateUtils.PATTERN_YYYYMMDD), new Date())) {
					GregorianCalendar calendar = new GregorianCalendar();
                    int hour = calendar.get(Calendar.HOUR_OF_DAY);
					if(mod.getTimePeriod() < hour)
                    return Result.failed("无效预约日期！");
                }
                Integer num = appointmentRecordService.queryRecordsByCardIdAndTime(qr.getIdcard(),mod.getTime(),mod.getTimePeriod());
                if(num == 0 || num == '0'){
                    // 预约名额
                    List<AppointmentQuota> quotas = appointmentQuotaMapper.queryQuota(mod.getBusinessId(), mod.getSysNo());
                    AppointmentQuota q = quotas.stream().filter(e -> Objects.equals(e.getTimePeriod(), mod.getTimePeriod())).findFirst().orElse(new AppointmentQuota());
                    List<AppointmentRecord> records = appointmentRecordService.queryAppointmentRecordsCount(mod.getSysNo(), mod.getBusinessId(), mod.getTime(), mod.getTimePeriod());
                    AppointmentRecord r = records.stream().findFirst().orElse(new AppointmentRecord());
                    if ((q.getQuota() - r.getCount()) <= 0) {
                        return Result.failed("抱歉，当前时间预约名额已满！");
                    }
                    List<AppointmentRecord> selfRecords = appointmentRecordService.queryRecordsByCardId(qr.getIdcard(), mod.getTime(), mod.getBusinessId(), null);
                    if (CollectionUtils.isNotEmpty(selfRecords)) {
                        return Result.failed("当前身份证已在当前时间预约了该业务！");
                    }
                    BusinessInfo b = appointmentRecordService.queryBusinessById(mod.getBusinessId());
                    if(b == null || b.getTypeName() == null){
                        return Result.failed("暂无查询到该业务数据！");
                    }
                    Appointment obj = Appointment.builder().id(UUID.randomUUID().toString())
                            .sysNo(mod.getSysNo())
                            .code(RandomUtils.buildRandomNumber())
                            .mobile(qr.getTell())
                            .name(qr.getName())
                            .nowDate(new Date())
                            .time(DateUtils.parseDate(mod.getTime(), DateUtils.PATTERN_YYYYMMDD))
                            .businessId(mod.getBusinessId())
                            .businessName(null != b ? b.getTypeName() : null)
                            .cardId(qr.getIdcard())
                            .startTime(DateUtils.setHours(DateUtils.parseDate(mod.getTime(), DateUtils.PATTERN_YYYYMMDD), mod.getTimePeriod()))
                            .endTime(DateUtils.setHours(DateUtils.parseDate(mod.getTime(), DateUtils.PATTERN_YYYYMMDD), (mod.getTimePeriod() + 1)))
                            .timePeriod(mod.getTimePeriod())
                            .matterId(mod.getMatterId())
                            .sysName(mod.getSysName())
                            .build();
                    appointmentRecordService.save(obj);
                    // 根据业务查询 网点的 平均等待时间、平均办理时间
                    HisQueue hisQueue = hisQueueService.getHistoryQueueTime(mod.getBusinessId(), mod.getSysNo());
                    // 根据业务查询 等待人数
                    QueueInfo queues = currentQueueService.getCurrentQueue(mod.getBusinessId(), mod.getSysNo());
                    ModAppointmentOut data = ModAppointmentOut.builder()
                            .cardId(qr.getIdcard().replaceAll("(\\w{6})(\\w+)(\\w{4})", "$1****$3"))
                            .finishTime(3)
                            .build();
                    if (null != hisQueue && null != queues) {
                        data.setFinishTime((long) hisQueue.getWaitTime() * queues.getWaitCount());
                    }
                    //异步请求发送微信通知
                    send.getWXInfo();
                    send.sendAppointmentValue(obj.getCardId(),obj.getBusinessName(),obj.getSysName(),DateUtils.setHours(DateUtils.parseDate(mod.getTime(), DateUtils.PATTERN_YYYYMMDD), mod.getTimePeriod()));
                    data.setAddress(hisQueueService.getAddressValue(mod.getSysNo()));
                    logger.error("【"+obj.getCardId()+"】添加预约："+data);
                    return Result.succeed(data, "预约成功");
                }else{
                    return Result.failed("当前日期时间段已预约过业务，请勿重复预约！");
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return Result.failed("预约失败！");
        }

    }


    /**
     * 取消预约
     *
     * @param obj
     * @return
     */
    public boolean cancel(CancelAppointment obj) {
        return appointmentRecordService.cancel(obj) > 0;
    }

    /**
     * 获取预约记录
     *
     * @return
     */
    public List<AppointmentRecordOut> findByCardId() {
        if (null == UserUtils.getUser()) {
            return null;
        } else {
            MobileUserQR qr = userService.getUserIdcard(UserUtils.getUser().getLoginName());
            if (null == qr) return null;
            return appointmentRecordService.queryRecordsByCardId(qr.getIdcard(), null, null, null)
                    .stream().map(e -> AppointmentRecordOut.builder()
                            .apptDate(DateUtils.formatDate(e.getApptDate(), DateUtils.PATTERN_YYYYMMDD))
                            .isTicket(e.getIsTicket())
                            .busName(e.getBusName())
                            .createDate(DateUtils.formatDate(e.getCreateDate(), DateUtils.DEFAULT_PATTERN))
                            .officeName(e.getOfficeName())
                            .timePeriod(e.getTimePeriod())
                            .id(e.getId())
                            .status(e.getStatus())
                            .businessid(e.getBusinessid())
                            .isDo(e.getIsDo())
                            .build()
                    ).collect(Collectors.toList());
        }
    }

    /**
     * 获取预约记录
     *
     * @return
     */
    public List<AppointmentRecordOut> recordsByWXId(String tell) {
        return appointmentRecordService.queryRecordsByTell(tell);
    }

    /**
     * 获取时间段信息
     *
     * @param t
     * @return
     */
    private ServiceTime.Detail getTimeDetails(Integer t) {
        return new ServiceTime.Detail(t + ":00-" + (t + 1) + ":00", t, 0);
    }


    /**
     * 设置推荐网点
     *
     * @param officesDetails
     */
    private void setRecommend(List<ServiceOffices.Detail> officesDetails) {
        if (CollectionUtils.isEmpty(officesDetails)) {
            return;
        }
        String typeName = "自助服务点";
        // 距离最近的网点
        ServiceOffices.Detail nearestOffices = officesDetails.stream().min(Comparator.comparing(ServiceOffices.Detail::getDistance)).orElse(null);
        if (null != nearestOffices) {
            if (null == nearestOffices.getRecommend()) {
                nearestOffices.setRecommend(new HashSet<>());
            }
            nearestOffices.getRecommend().add(RecommendEnums.NEAREST.getCode());
        }
        // 等待最短的网点
        officesDetails.stream().filter(d -> !Objects.equals(d.getType(), typeName)).min(Comparator.comparing(ServiceOffices.Detail::getWaitTime)).ifPresent(e -> {
            if (null == e.getRecommend()) {
                e.setRecommend(new HashSet<>());
            }
            e.getRecommend().add(RecommendEnums.SHORTEST_WAIT.getCode());
        });
        // 办件最快的网点
        officesDetails.stream().filter(d -> !Objects.equals(d.getType(), typeName)).min(Comparator.comparing(ServiceOffices.Detail::getHandleTime)).ifPresent(e -> {
            if (null == e.getRecommend()) {
                e.setRecommend(new HashSet<>());
            }
            e.getRecommend().add(RecommendEnums.FASTEST_SERVICE.getCode());
        });

        // 从三个推荐中计算智能推荐
        for (ServiceOffices.Detail d : officesDetails) {
            // 距离大于上限（公里）不作为智能推荐
            if (d.getDistance() > GuideConstant.OFFICES_DISTANCE_UPPER_LIMIT || d.getTotalTime() == GuideConstant.OFFICES_LIMIT_TIME) {
                d.setTotalTime(GuideConstant.OFFICES_LIMIT_TIME);
                continue;
            }
            // 路程时长 = 小于2km ? 距离 * 4分钟（骑行） ： 距离 * 2分钟(驾车)
            Double duration = d.getDistance() <= GuideConstant.OFFICES_DISTANCE_LOWER_LIMIT ? d.getDistance() * GuideConstant.DRIVE_CYCLING_DURATION : d.getDistance() * GuideConstant.DRIVE_DEFAULT_DURATION;
            // 总时长 = （平均等待时长 * 当前等待人数） + 路程时长
            d.setTotalTime((d.getWaitTime() * d.getWaitNum()) + duration);
        }
        ServiceOffices.Detail aiOffices = officesDetails.stream().filter(e -> !Objects.equals(GuideConstant.OFFICES_LIMIT_TIME, e.getTotalTime()) && !Objects.equals(e.getType(), typeName)).min(Comparator.comparing(ServiceOffices.Detail::getTotalTime)).orElse(null);
        if (null != aiOffices) {
            if (null == aiOffices.getRecommend()) {
                aiOffices.setRecommend(new HashSet<>());
            }
            aiOffices.getRecommend().add(RecommendEnums.AI.getCode());
        } else if (null != nearestOffices) {
            nearestOffices.getRecommend().add(RecommendEnums.AI.getCode());
        }
    }


    /**
     * 获取事项的服务网点
     *
     * @param matterId 事项id
     * @return
     */
    private List<Offices> getServeOffices(String matterId) {
        if (StringUtils.isEmpty(matterId)) {
            return null;
        }
        List<String> values = null;
        List<Map<String,String>> map = mobileQueueService.getCloseValue();
        if(!map.isEmpty()){
            values = new ArrayList<String>();
            for(Map<String,String> m : map){
                if(null != m.get("areaId"))
                values.add(m.get("areaId"));
            }
        }
        List<String> areaIds = matterAreaMapper.selectByMatterId(matterId,values);
        if (CollectionUtils.isEmpty(areaIds)) {
            return null;
        }
        List<MatterArea> matterAreas = hisQueueService.queryAreaById(areaIds);
        // 过滤出 唯一标识、经纬度不为空的网点a
        matterAreas = matterAreas.stream().filter(e -> StringUtils.isNotEmpty(e.getExpr()) && StringUtils.isNotEmpty(e.getLe()) && StringUtils.isNotEmpty(e.getLo())).collect(Collectors.toList());
        return matterAreas.stream().map(e ->
                Offices.builder()
                        .id(e.getExpr())
                        .title(e.getAreaName())
                        .address(e.getAddress())
                        .longitude(Double.valueOf(e.getLo()))
                        .latitude(Double.valueOf(e.getLe()))
                        .tel(e.getTell())
                        .type(e.getAreaType())
                        .build()).collect(Collectors.toList());
    }


    /**
     * 根据事项id,获取业务id
     *
     * @param matterId 事项id
     * @return
     */
    private Map<String, BusinessInfo> queryAreaBusiness(String matterId, List<String> areaId) {

        // 查询事项对应的业务id
        List<BusinessInfo> businessInfos = mobileMatterMapper.selectBusinessIdByMatterId(matterId, areaId);

        if (CollectionUtils.isEmpty(businessInfos)) {
            return new HashMap<>();
        }
        // 转map,一个区域对应一个业务
        return businessInfos.stream().collect(Collectors.toMap(BusinessInfo::getAreaId, Function.identity(), (o1, o2) -> o1));

    }


    /**
     * 获取当前日期的前几周日期
     * getBeforeWeek方法
     *
     * @return void
     * @author hankongbin
     * data: Dec 18, 2018
     */
    private static List<WorkdayInfo> getBeforeWeek(int beforeWeek) {
        String[] week = new String[]{"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        List<WorkdayInfo> wdlist = new ArrayList<WorkdayInfo>();
        // 日期格式转换
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // 当前日期
        Calendar instance = Calendar.getInstance();
        // 调整到上周
        instance.add(Calendar.WEDNESDAY, beforeWeek);
        // 调整到上周1
        instance.set(Calendar.DAY_OF_WEEK, 2);
        //循环打印
        for (int i = 1; i <= 6; i++) {
            WorkdayInfo workday = new WorkdayInfo();
            workday.setWeekday(week[Integer.parseInt(String.valueOf(i)) - 1]);
            workday.setTime(format.format(instance.getTime()));
            wdlist.add(workday);
            instance.add(Calendar.DAY_OF_WEEK, 1);
        }
        return wdlist;
    }


}
